package gold.digger;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC60 {
    public long startExecuteTime = System.currentTimeMillis();

    //Input: n = 3, k = 3
//Output: "213"
    class Solution {

        public Map<Integer, Integer> map = new HashMap<>();

        public String getPermutation(int n, int k) {
            List<Integer> candidateNumList = new ArrayList<>();
            for (int i = 1; i <= n; i++) {
                candidateNumList.add(i);
            }

            StringBuilder sb = new StringBuilder();
            getPermutationRecur(candidateNumList, k - 1, sb);
            return sb.toString();
        }

        public void getPermutationRecur(List<Integer> candidateNumList, int k, StringBuilder sb) {
            if (k == 0) {
                for (Integer num : candidateNumList) {
                    sb.append(String.valueOf(num));
                }

                return;
            }

            int minusNCount = getFactorN(candidateNumList.size() - 1);
            int firstNumPos = k / minusNCount;
            sb.append(candidateNumList.get(firstNumPos));
            candidateNumList.remove(firstNumPos);
            k %= minusNCount;
            getPermutationRecur(candidateNumList, k, sb);
        }

        public int getFactorN(int n) {
            if (map.containsKey(n)) return map.get(n);
            int res = 1;
            for (int i = 2; i <= n; i++) {
                res *= i;
            }

            map.put(n, res);
            return res;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.getPermutation(3, 3));
    }

    public static void main(String[] args) throws Exception {
        LC60 an = new LC60();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
